/**
 * 
 */
package com.umakr.ax.core.base;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Maps;
import com.umakr.ax.core.Constants;
import com.umakr.ax.core.exception.BaseException;
import com.umakr.ax.core.mybatis.proxy.PageCustom;
import com.umakr.ax.core.support.HttpCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.umakr.ax.core.exception.IllegalParameterException;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.plugins.Page;

/**
 * 控制器基类
 * @author gx
 */
public abstract class BaseController {
	protected final Log logger = LogFactory.getLog(this.getClass());

	private static final String ERRORCODE = "errorCode";

	/** 获取当前用户Id */
	protected Long getCurrUser() {
		return -1L;
	}

	/** 设置成功响应代码 */
	protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap) {
		return setSuccessModelMap(modelMap, null);
	}

	/** 设置成功响应代码 */
	protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap, Object data) {
		return setModelMap(modelMap, HttpCode.OK, data);
	}

	/** 设置响应代码 */
	protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code) {
		return setModelMap(modelMap, code, null);
	}

	/** 设置响应代码 */
	protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) {
		Map<String, Object> map = new LinkedHashMap<>();
		map.putAll(modelMap);
		modelMap.clear();
		if (data != null) {
			if (data instanceof Page) {

				modelMap.put(ERRORCODE, 1);
				modelMap.put("msg", "");
				Map<String, Object> resultMap = Maps.newHashMap();
				Page<?> page = (Page<?>) data;
				resultMap.put("list", page.getRecords());
				resultMap.put("pageNo", page.getCurrent());
				resultMap.put("pageSize", page.getSize());
				resultMap.put("pageCount", page.getPages());
				resultMap.put("total", page.getTotal());
				if(data instanceof PageCustom&&!((PageCustom)data).isEmpty()){
					resultMap.putAll(((PageCustom)data).getOtherParameters());
				}
				modelMap.put("data", resultMap);
			} else if (data instanceof List<?>) {
				modelMap.put(ERRORCODE, 1);
				modelMap.put("msg", "");
				modelMap.put("data", data);
				modelMap.put("iTotalRecords", ((List<?>) data).size());
				modelMap.put("iTotalDisplayRecords", ((List<?>) data).size());
			}  else if (data instanceof Map<?,?>) {
				Map<String, Object> resultMap = (Map<String,Object>)data;
				modelMap.put(ERRORCODE, resultMap.get(ERRORCODE));
				modelMap.put("msg", resultMap.get("msg"));
				modelMap.put("data", resultMap.get("data"));
			} else if (data instanceof Object) {
				modelMap.put(ERRORCODE,1);
				modelMap.put("msg", "");
				modelMap.put("data", data);
			}
			else {
				modelMap.put(ERRORCODE, code.value());
				modelMap.put("msg", code.msg());
			}
		}
		return ResponseEntity.ok(modelMap);
	}

	/** 异常处理 */
	@ExceptionHandler(Exception.class)
	public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
			throws Exception {
		logger.error(Constants.EXCEPTION_HEAD, ex);
		ModelMap modelMap = new ModelMap();
		if (ex instanceof BaseException) {
			((BaseException) ex).handler(modelMap);
		} else if (ex instanceof IllegalArgumentException) {
			new IllegalParameterException(ex.getMessage()).handler(modelMap);
		} else {
			modelMap.put("httpCode", HttpCode.INTERNAL_SERVER_ERROR.value());
			String msg = StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.INTERNAL_SERVER_ERROR.msg());
			modelMap.put("msg", msg.length() > 100 ? "系统走神了,请稍候再试." : msg);
		}
		response.setContentType("application/json;charset=UTF-8");
		modelMap.put("timestamp", System.currentTimeMillis());
		logger.info(JSON.toJSON(modelMap));
		byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
		response.getOutputStream().write(bytes);
	}

	public abstract <T extends BaseService> T  getService();
	public abstract <T extends BaseService> T  getService(Class<T> clazz);
}
